import requests

import random



import time

from BloodSpiderModel.BloodSpiderPrint.blood_spider_print_logger import BloodSpiderPrintLogger


# 辅助类
class WzryOrderHelper:
    def __init__(self, wzry_api_url: str) -> None:
        self.wzry_api_url = wzry_api_url
    # 随机延迟
    def random_delay(self, min_delay: int = 1, max_delay: int = 3) -> None:
        """
        随机延迟，默认1-3秒
        """
        # 随机延迟
        delay = random.randint(min_delay, max_delay)
        time.sleep(delay)
    # 获取B平台的目前余额
    def get_factory_balance(self) -> float:
        response = requests.get(f"{self.wzry_api_url}dlwz/GetMyBalance/").json()
        return response['data']['data']['balance']

    # 取消在B平台的订单
    def cancel_order(self,wzry_api_url: str, order_id: str, user_id: str) -> None:
        print(requests.get(f"{wzry_api_url}dlwz/CancelOrder/", params={"OrderID": order_id}, headers={"user-id": user_id}).json())

class Main:
    def __init__(self) -> None:
        # 服务器的API
        self.api_url = "http://localhost:9001/api"
        # 王者荣耀的API
        self.wzry_api_url = f"{self.api_url}/game/wzry/"
        # 日志
        self.logger = BloodSpiderPrintLogger()
        # 辅助类
        self.order_helper = WzryOrderHelper(self.wzry_api_url)
        # 服务器要求提供的user-id
        self.user_id = "a823b77b-4cf3-4533-a92f-4cd7c52128eb"
        


  

    """
    车间1: 抓单车间（盯着A平台的新订单）
    规则1: 保证金大于10元的统一不要
    """
    def run_workshop1(self) -> list:
        order_list = []
        response = requests.get(f"{self.wzry_api_url}dlt/LevelOrderList/", params={
            "Price_Str": "20_40"
        }).json()
        for order in response["data"]['LevelOrderList']:
            if order["Ensure"] > 10:
                continue
        
            order_list.append(order)
        return order_list


    """
    车间2: 大脑（真正决定干不干这单）
    """
    def run_workshop2(self) -> bool:
        # 访问服务器是否还有钱
        if requests.get(f"{self.api_url}/status_manage/dlwz_check_balance_enough/").json()["data"]:
            return True
        return False


    """
    车间3: 在B平台把单子挂出去（发单车间）
    """
    def run_workshop3(self, order: dict) -> bool:
        order["account_id"] = "0e85bfa5-6f81-4d93-b905-7bd90cb6397d"

        # 下单
        response = requests.get(f"{self.wzry_api_url}dlwz/PublishOrder/", params=order, headers={"user-id": self.user_id}).json()
        if response["code"] == 0:
            self.logger.blood_spider_print_info(f"下单成功: {response['data']['order_info']['order_name']} | 价格: {response['data']['order_info']['posting_price']} 元")
        else:
            self.logger.blood_spider_print_error(f"下单失败: {response}, {order}")
            if "充值" in response["message"]:
                # 通知服务器保证金不足
                self.logger.blood_spider_print_info("保证金不足, 通知服务器保证金不足")
                requests.get(f"{self.api_url}/status_manage/dlwz_check_balance_enough/", params={"status": False, "action": "set"}).json()
                self.order_helper.cancel_order(self.wzry_api_url,response["data"]["tradeNo"], self.user_id)
                return False
        # 随机延迟
        self.order_helper.random_delay(3, 10)
        return True
            
    """
    车间6: 检查A平台的原单是否还存在, 如果不存在, 就取消在B平台的订单
    """
    def run_workshop6(self):
        
        while True:
            # 获取数据库中的全部订单
            response = requests.get(f"{self.wzry_api_url}order/list/", params={ "status": 1}, headers={"user-id": self.user_id}).json()
            if len(response["data"]) == 0:
                self.logger.blood_spider_print_debug(f"当前数据库中没有订单")
                # 获取余额如果大于10
                if float(self.order_helper.get_factory_balance()) > 10:
                    # 通知服务器有钱
                    self.logger.blood_spider_print_info("数据库没有订单,但是余额大于10, 通知服务器有钱")
                    requests.get(f"{self.api_url}/status_manage/dlwz_check_balance_enough/", params={"status": True, "action": "set"}).json()
                else:
                    # 通知服务器没有钱
                    self.logger.blood_spider_print_info("数据库没有订单,并且余额小于等于10, 通知服务器没有钱")
                    requests.get(f"{self.api_url}/status_manage/dlwz_check_balance_enough/", params={"status": False, "action": "set"}).json()
            for order in response["data"]:
                # 检查原订单是否存在
                self.logger.blood_spider_print_debug(f"检查订单是否存在: {order['order_source_id']}")
                search_order_response = requests.get(f"{self.wzry_api_url}dlt/SearchOrderExist/", params={"OrderID": order["order_source_id"]}).json()
                if search_order_response["code"] != 0:
                    CancelOrderResponse = requests.get(f"{self.wzry_api_url}dlwz/CancelOrder/", params={"OrderID": order["posting_platform_id"]}).json()
                    if CancelOrderResponse["data"]["code"] == 10000 and CancelOrderResponse["code"] == 0:
                        self.logger.blood_spider_print_info(f"取消订单成功: {order['order_name']} | 价格: {order['posting_price']} 元")
                        # 通知服务器已经成功取消了一个订单
                        requests.get(f"{self.api_url}/status_manage/dlwz_check_balance_enough/", params={"status": True, "action": "set"}).json()
                    else:
                        self.logger.blood_spider_print_debug(f"服务器返回的内容: {CancelOrderResponse}")
                        self.logger.blood_spider_print_error(f"取消订单失败: {CancelOrderResponse['message']}")
                else:
                    self.logger.blood_spider_print_debug(f"订单: {order['order_name']} | 价格: {order['posting_price']} 元, 原订单还存在")
    

            # 随机延迟
            self.order_helper.random_delay(60, 120)
    
    """
    工厂
    得到当前B平台的余额, 低于10元统一暂停工厂运行
    """
    def run_factory(self) -> None:
        while True:
            try:
                if not requests.get(f"{self.api_url}/status_manage/dlwz_check_balance_enough/").json()["data"]:
                    self.logger.blood_spider_print_error(f"当前B平台余额不足, 暂停工厂运行")
                    # 随机延迟
                    self.order_helper.random_delay(10, 60)
                    continue
                # 获取B平台的目前余额
                balance = self.order_helper.get_factory_balance()
                if float(balance) < 10:
                    self.logger.blood_spider_print_error(f"当前B平台余额: {balance} 元, 低于10元, 暂停工厂运行")
                    # 通知服务器余额不足
                    requests.get(f"{self.api_url}/status_manage/dlwz_check_balance_enough/", params={"status": False, "action": "set"}).json()
                    continue
                run_workshop1: list = self.run_workshop1()
                self.logger.blood_spider_print_info(f"当前B平台余额: {balance} 元, 抓到{len(run_workshop1)}个新订单")
                for order in run_workshop1:
                    # 大脑判断是否要干这单
                    if not self.run_workshop2():
                        self.logger.blood_spider_print_error(f"大脑拒绝该单: {order['Title']} | 价格: {order['Price']} 元")
                        continue
                    
                    # 下单
                    if not self.run_workshop3(order):
                        self.logger.blood_spider_print_error(f"下单失败: {order['Title']} | 价格: {order['Price']} 元")
                    # 随机延迟
                    self.order_helper.random_delay(3, 10)
                
                # 随机延迟
                self.order_helper.random_delay(60, 120)
            except Exception as e:
                self.logger.blood_spider_print_error(f"工厂运行出错: {e}")
                # 随机延迟
                self.order_helper.random_delay(10, 60)
                continue


if __name__ == "__main__":
    main = Main()
    print(f"请选择你的运行模式: 1. 工厂模式 2. 车间6模式")
    mode = input()
    if mode == "1":
        main.run_factory()
    elif mode == "2":
        main.run_workshop6()
    else:
        print(f"输入错误, 请输入1或2")
